package com.gh.config;

import com.gh.anno.Strategy;
import com.gh.strategy.GetSumStrategy;
import com.gh.strategy.ProductStrategy;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author heyu
 * @date 2022:11:06 10:00
 * 实现 ApplicationContextAware 容器一启动就加载策略
 */
@Component
public class StrategyContext implements ApplicationContextAware {

    private ApplicationContext ctx;
    private Map<String, ProductStrategy> strategyMap = new HashMap<>();
    private Map<String, GetSumStrategy> sumStrategyMap = new HashMap<>();


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ctx = applicationContext;
        Map<String, ProductStrategy> map = ctx.getBeansOfType(ProductStrategy.class);
        map.values().stream().forEach(v -> {
            String strategy = v.getClass().getAnnotation(Strategy.class).value();
            strategyMap.put(strategy, v);
        });

        Map<String, GetSumStrategy> map1 = ctx.getBeansOfType(GetSumStrategy.class);
        map1.values().stream().forEach(v -> {
            String annotation = v.getClass().getAnnotation(Strategy.class).value();
            sumStrategyMap.put(annotation, v);
        });
    }

    public ProductStrategy getProductStrategy(String proStrategyType) {
        return strategyMap.get(proStrategyType);
    }

    public GetSumStrategy getGetSumStrategy(String sumStrategyType) {
        return sumStrategyMap.get(sumStrategyType);
    }
}
